<template>
	<view class="ccii_login">
		<!-- #ifdef APP-PLUS || MP-QQ || H5-->
		<view class="content">
			<view class="ccii_logo">
				<image src='https://oss-shop.cciinet.com/files/MiniProgram/login_logo.png'>
			</view>
			<!--  #ifdef APP-PLUS  -->
			<web-view v-if="webStu" src="/hybrid/html/view/code.html" @message="handleMessage"></web-view>
			<!-- #endif -->
			<!--  #ifdef MP-QQ  -->
			<web-view v-if="webStu" src="https://oss-shop.cciinet.com/files/MiniProgram/code.html" @message="handleMessage"></web-view>
			<!-- #endif -->
			<!--  #ifdef H5  -->
			<!-- #endif -->
			<view class="input_box fs_28">
				<input type="digit" pattern="\d*" v-model="mobile" maxlength="11" placeholder="请输入手机号码">
				<i class="iconfont icon-guanbi1" v-if="hasMobile" @click="mobile=''"></i>
				<!--  #ifdef APP-PLUS ||  MP-QQ -->
				<button class="code_btn" :class="isRightMobile?'c_blue':'c_999'" @click="isRightMobile&&codetxt=='获取验证码'&&openTencentCaptcha()"
				 v-html="codetxt"></button>
				<!-- #endif -->
				<!--  #ifdef H5 -->
				<button class="code_btn" :class="isRightMobile?'c_blue':'c_999'" @click="isRightMobile&&codetxt=='获取验证码'&&openTencentCaptcha1()"
				 v-html="codetxt"></button>
				<!-- #endif -->
			</view>
			<view v-show="isShowCodeInput" class="codes">
				<input class="hidden_input" ref="hidden_input" type="digit" pattern="\d*" maxlength="6" v-model="code" @paste="handlePaste($event)"
				 @keyup="code=code.replace(/\D/g,'')">
				<view class="input_code">
					<view class="ul">
						<view class="li">{{code.length>=1?code[0]:''}}</view>
						<view class="li">{{code.length>=2?code[1]:''}}</view>
						<view class="li">{{code.length>=3?code[2]:''}}</view>
						<view class="li">{{code.length>=4?code[3]:''}}</view>
						<view class="li">{{code.length>=5?code[4]:''}}</view>
						<view class="li">{{code.length>=6?code[5]:''}}</view>
					</view>
				</view>
			</view>
			<view class="agreement clearfix">
				<view class="fl check" @click="checked=!checked">
					<view v-show="checked" class="dot"></view>
				</view>
				<view class="p c_666 fs_22">我已经阅读并同意<span @click="$handleOpenUrl('/pages/agreement/index?type=1',99)">《平台注册协议》</span><span
					 @click="$handleOpenUrl('/pages/agreement/index?type=2',99)">《隐私政策》</span><span @click="$handleOpenUrl('/pages/agreement/index?type=3',99)">《商家入驻协议》</span>
				</view>
			</view>
			<button class="account_btn" @click="handleAccountLogin">登录</button>
			<p class="tip_txt">未注册的手机号码验证后自动为您创建账户</p>
			<view class="btn" @click="$handleOpenUrl('/pages/home/index',0)">暂不登录</view>
			<!--  #ifdef H5 -->
			<view class="bottom_box c_999">
				<view class="text_box">
					<span class="text fs_24">第三方账号登录</span>
				</view>
				<view class="weixin_box" @click="handleWXLogin">
					<image :src="'https://oss-shop.cciinet.com/files/MiniProgram/weixin_logo.png'" alt="">
						<span class="fs_24">微信登录</span>
				</view>
			</view>
			<!-- #endif -->
		</view>
		<!-- #endif -->
		<!-- #ifdef MP-WEIXIN -->
		<view class="wx_login">
			<image src="https://oss-shop.cciinet.com/files/MiniProgram/login_bg.png" mode="widthFix"></image>
			<button open-type="getPhoneNumber" hover-class="none" @getphonenumber="handleOpenUrl">
				微信授权登录
			</button>
			<view class="btn" @click="$handleOpenUrl('/pages/home/index',0)">
				暂不登录
			</view>
		</view>
		<!-- #endif -->
	</view>
</template>
<script>
	import {
		getUserInfo,
		getCaptcha,
		checkMobileExistCode,
		loginOrRegister,
		wxLogin,
		checkRelationMobile,
		weChatLogin,
		getOpenId
	} from "@/api/login/index.js"
	import {
		checkImage
	} from "@/api/common/index.js"
	export default {
		data() {
			return {
				checked: false,
				auth: "",
				// showKeyboard: false,
				isShowCodeInput: false,
				mobile: '',
				code: '',
				timer: null,
				codetxt: '获取验证码',
				platformSource: '', // 注册渠道   0 PC   1 H5   2 微信手机号  3 app  4 小程序  21 微信授权   31 苹果app
				webStu: false,
				platformSource1: "",
				appid: "wx4c9aa91288aee984",
				redirect_uri: "https://m.cciinet.com/pages/login/index",
				codeUrl: ""
			}
		},
		onLoad(option) {
			// #ifdef APP-PLUS 
			//this.handleLoginAuth()
			// #endif 

			// #ifdef H5 
			// this.appid = process.env.NODE_ENV === 'production' ? 'wx98d5e9c98ab45b95' : 'wx98d5e9c98ab45b95' //h5 wx4c9aa91288aee984
			this.codeUrl = this.getUrlCode().code || ""
			if (this.codeUrl) {
				debugger
				this.handleCodeLogin()
			}
			console.log(this.codeUrl)
			var ua = navigator.userAgent.toLowerCase(); // 获取判断用的对象
			if (ua.match(/MicroMessenger/i) == "micromessenger") {
				// 微信中打开
				this.platformSource1 = 2
			} else {
				// 外部浏览器
				this.platformSource1 = 1
			}
			uni.setStorageSync("h5_promoterNumber", option.promoterNumber || ""); // 推广者编号
			// #endif 
		},
		computed: {
			isRightMobile() {
				const phoneReg = /^1[3456789]\d{9}$/
				return phoneReg.test(this.mobile.trim())
			},
			hasMobile() {
				if (this.mobile) {
					return true
				}
				return false
			}
		},
		methods: {
			// 触发滑块验证H5
			openTencentCaptcha1() {
				let Imgcaptcha = new TencentCaptcha("2080837798", res => {
					if (res.ret === 0) {
						this.handleCheckImage(res)
					} else {
						uni.showToast({
							icon: "none",
							title: "请完成滑块验证"
						})
					}
				}, {});
				Imgcaptcha.show();
			},
			// H5微信授权登录
			handleWXLogin() {
				if (!this.checked) {
					uni.showToast({
						icon: "none",
						title: "请阅读并同意相关协议"
					})
					return
				}
				window.location.href =
					`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${this.appid}&redirect_uri=${encodeURIComponent(this.redirect_uri)}&response_type=code&scope=snsapi_userinfo&state=${this.makeState}#wechat_redirect`
			},
			makeState() {
				return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)
			},
			handleCodeLogin() {
				wxLogin({
					code: this.codeUrl
				}).then(res1 => {
					if (res1.code === 0) {
						uni.setStorageSync('openid', res1.data.openid)
						checkRelationMobile({
							openid: res1.data.openid
						}).then(res2 => {
							if (res2.code === 0) {
								if (res2.data) {
									// 该微信已关联手机号
									weChatLogin({
										mobile: res2.data[0].mobile,
										platformSource: 21
									}).then(res => {
										if (res.code === 0) {
											uni.setStorageSync('userId', res.data.user.id)
											uni.setStorageSync('userInfo', JSON.stringify(res.data))
											this.$handleOpenUrl('/pages/home/index', 0)
										}
									})
								} else {
									// 反之  去关联手机号页面
									this.$handleOpenUrl('/pages/login/phone', 99)
								}
							} else {
								alert(3)
								this.$handleOpenUrl("/pages/login/index")
							}
						})
					} else {
						alert(4)
						this.$handleOpenUrl("/pages/login/index")
					}
				})
			},
			getUrlCode() { // 截取url中的code方法
				var url = location.search
				var theRequest = new Object()
				if (url.indexOf("?") != -1) {
					var str = url.substr(1)
					var strs = str.split("&")
					for (var i = 0; i < strs.length; i++) {
						theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1])
					}
				}
				return theRequest
			},
			//接受webview
			handleMessage(e) {
				console.log(e)
				let codeStu = e.detail.data[0].codeStu
				if (codeStu) {
					this.webStu = false
					this.handleCheckImage(JSON.parse(e.detail.data[0].str))
				} else {
					this.webStu = false
				}
			},
			// 校验图形验证码
			async handleCheckImage(v) {
				let res = await checkImage({
					randstr: v.randstr,
					ticket: v.ticket
				})
				if (res.code == 0 && res.data.CaptchaCode == 1) {
					this.getCode()
				} else {
					uni.showToast({
						title: res.data.CaptchaMsg,
						icon: 'none'
					});
				}
			},
			// 获取短信验证码
			async getCode() {
				let res = await getCaptcha({
					mobile: this.mobile,
				});
				console.log(res)
				if (res.code == 0) {
					uni.showToast({
						title: "验证码已发送"
					});
					this.isShowCodeInput = true
					let n = 120;
					this.timer = setInterval(() => {
						this.codetxt = `${n--}s`;
						if (n == 0) {
							this.codetxt = "获取验证码";
							clearInterval(this.timer);
						}
					}, 1000);
				} else {
					this.isShowCodeInput = false
					uni.showToast({
						title: res.msg,
						icon: 'none'
					});
				}
			},
			openTencentCaptcha() {
				this.webStu = true
			},
			// 手机号登录操作
			async handleAccountLogin() {
				if (!this.isRightMobile) {
					uni.showToast({
						title: '请输入正确手机号',
						icon: 'none'
					});
					return
				}
				if (!this.code) {
					uni.showToast({
						title: '请输入正确验证码',
						icon: 'none'
					});
					return
				}
				if (!this.checked) {
					uni.showToast({
						title: '请阅读并同意相关协议',
						icon: 'none'
					});
					return
				}
				// 检查手机号是否已注册
				let res = await checkMobileExistCode({
					mobile: this.mobile,
					captcha: this.code
				})
				if (res.code == 0) {
					if (res.data) {
						// 手机号已注册  直接登录
						this.handleLogin(1)
					} else {
						// 手机号未注册  去上传营业执照页
						this.handleLogin(2)
					}
				} else {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					});
				}
			},
			//app登录判断接口
			async handleLogin(stu) {
				let res = await loginOrRegister({
					captcha: this.code,
					mobile: this.mobile,
					// #ifdef APP-PLUS
					platformSource: uni.getSystemInfoSync().platform == 'ios'?3:31, //苹果app 3 安卓app 31
					// #endif 
					// #ifdef MP-QQ
					platformSource: 41, // qq小程序
					// #endif 
					// #ifdef H5
					platformSource: this.platformSource1,
					// #endif 
				})
				if (res.code === 0) {
					uni.setStorageSync('userId', res.data.user.id)
					uni.setStorageSync('userInfo', JSON.stringify(res.data))
					if (stu == 1) {
						this.$handleOpenUrl('/pages/home/index', 0)
					} else {
						this.$handleOpenUrl('/pages/login/label?id=1')
					}
				} else {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					});
				}
			},
			//微信授权登录
			handleOpenUrl(res) {
				console.log(res)
				if (res.detail.errMsg=="getPhoneNumber:ok") {
					let session_key = uni.getStorageSync('session_key')
					if (!uni.getStorageSync('session_key') || !uni.getStorageSync('openid')) {
						uni.login({
							success: data => {
								getOpenId({
									code: data.code
								}).then(ress => {
									if (ress.code === 0) {
										uni.setStorageSync('openid', ress.data.openid)
										uni.setStorageSync('session_key', ress.data.session_key)
										this.handleOpenUrl(res)
									}
								})
							}
						})
						return;
					}
					getUserInfo({
						encryptedData: res.detail.encryptedData,
						iv: res.detail.iv,
						sessionKey: session_key,
						openid: uni.getStorageSync('openid'),
					}).then(res => {
						if (res.code === 0) {
							uni.setStorageSync('userId', res.data.user.id)
							uni.setStorageSync('userInfo', JSON.stringify(res.data))
							if (res.data.registered) {
								this.$handleOpenUrl('/pages/home/index', 0)
							} else {
								this.$handleOpenUrl('/pages/login/label?id=1')
							}
						} else {
							uni.showToast({
								title: res.msg,
								icon: "none"
							})
						}
					})
				}
			},
			//获取app登录权限
			handleLoginAuth() {
				uni.getProvider({
					service: 'oauth',
					success: res => {
						this.auth = res.provider.join(',')
						if (this.auth.indexOf('univerify') != -1) {
							this.handleBeforeOneClickLogin()
						} else {
							uni.showToast({
								title: "暂不支持一键登录请选择其他登录方式"
							})
						}
					}
				});
			},
			//一键登录
			handleBeforeOneClickLogin() {
				let that = this
				uni.preLogin({
					provider: 'univerify',
					success(res) { //预登录成功
						console.log(res)
						that.handleOneClickLogin()
						// 显示一键登录选项
					},
					fail(res) { // 预登录失败
						// 不显示一键登录选项（或置灰）
						// 根据错误信息判断失败原因，如有需要可将错误提交给统计服务器
						console.log(res)
						console.log(res)
					}
				})
			},
			handleOneClickLogin() {
				uni.login({
					provider: 'univerify',
					univerifyStyle: { // 自定义登录框样式
						"backgroundColor": "#ffffff",
						"icon": {
							"path": "static/assets/login-logo.png"
						},
						"privacyTerms": {
							"privacyItems": [
								// 自定义协议条款，最大支持2个，需要同时设置url和title. 否则不生效  
								{
									"url": "https://m.cciinet.com/agreement?type=1", // 点击跳转的协议详情页面  
									"title": "《用户服务协议》" // 协议名称  
								},
								{
									"url": "https://m.cciinet.com/agreement?type=2", // 点击跳转的协议详情页面  
									"title": "《隐私政策》" // 协议名称  
								}
							]
						}
					},
					success(res) { // 登录成功
						console.log(res); // {openid:'登录授权唯一标识',access_token:'接口返回的 token'}
					},
					fail(res) { // 登录失败
						uni.closeAuthView()
					}
				})
			}

		}
	}
</script>
<style lang="scss" scoped>
	.ccii_login {
		height: 100%;

		.codes {
			position: relative;
			margin-top: 15upx;

			.hidden_input {
				position: absolute;
				bottom: 5upx;
				height: 60upx;
				width: 100%;
				z-index: 666;
				opacity: 0;
			}

			.input_code {
				.ul {
					display: flex;
					height: 60upx;
					width: 100%;

					.li {
						margin-right: 10upx;
						border-bottom: 2upx solid #999999;
						font-size: 32upx;
						display: flex;
						justify-content: center;
						align-items: center;
						box-pack: center;
						flex: 1;
					}

					.li:last-child {
						margin-right: 0upx;
					}
				}
			}
		}

		.wx_login {
			width: 100%;

			image {
				width: 100%;
			}

			button {
				display: block;
				width: 520upx;
				height: 88upx;
				line-height: 88upx;
				background: linear-gradient(87deg, #035ABE, #218EED);
				border-radius: 44upx;
				color: #ffffff;
				text-align: center;
				font-size: 34upx;
				margin: 60upx auto 17upx;
			}


		}

		.btn {
			display: block;
			width: 520upx;
			height: 88upx;
			line-height: 88upx;
			background: #fff;
			border-radius: 44upx;
			color: #ffffff;
			text-align: center;
			font-size: 34upx;
			margin: 60upx auto 17upx;
			border: 1upx solid #035ABE;
			color: #035ABE;
		}

		.content {
			height: calc(100% - 88upx);
			padding: 63upx 78upx 0;

			.ccii_logo {
				height: 184upx;
				width: 163upx;
				margin: 0 auto 80upx;

				image {
					height: 100%;
					width: 100%;
				}
			}

			.agreement {
				margin-top: 20upx;
				display: flex;
				justify-content: center;

				.check {
					display: flex;
					justify-content: center;
					align-items: center;
					width: 25upx;
					height: 25upx;
					border: 2upx solid #999999;
					border-radius: 50%;
					margin-right: 10px;

					.dot {
						width: 80%;
						height: 80%;
						border-radius: 50%;
						background-color: #004899;
					}
				}

				.p {
					display: inline-block;
					width: 560upx;
					font-size: 22upx;
					color: #666666;
				}
			}

			.input_box {
				position: relative;
				width: 100%;
				height: 65upx;
				line-height: 65upx;
				border-bottom: 2upx solid #CCCCCC;
				display: flex;
				justify-content: center;

				input {
					height: 60upx;
					width: 100%;
				}

				.icon-guanbi1 {
					position: absolute;
					right: 200upx;
					color: #000;
					font-size: 34upx;
				}

				.code_btn {
					position: absolute;
					right: 0;
					height: 60upx;
					line-height: 60upx;
					font-size: 28upx;
					z-index: 999999;
				}

				.c_blue {
					color: #00428E;
				}
			}

			.account_btn {
				display: block;
				width: 520upx;
				height: 88upx;
				line-height: 88upx;
				background: linear-gradient(87deg, #035ABE, #218EED);
				border-radius: 44upx;
				color: #ffffff;
				text-align: center;
				font-size: 34upx;
				margin: 60upx auto 17upx;
			}

			.tip_txt {
				font-size: 20upx;
				color: #666666;
				text-align: center;
			}

			.bottom_box {
				margin-top: 100upx;
				height: 230upx;
				display: flex;
				flex-direction: column;
				align-items: center;

				.text_box {
					position: relative;

					.text::after,
					.text::before {
						content: '';
						height: 2upx;
						width: 150upx;
						position: absolute;
						top: 50%;
						background: #ccc;
					}

					.text::after {
						left: 200upx;
					}

					.text::before {
						right: 200upx;
					}
				}

				.weixin_box {
					display: flex;
					flex-direction: column;
					justify-content: center;
					align-items: center;

					image {
						height: 88upx;
						width: 88upx;
						margin: 40upx 0 16upx;
					}
				}
			}
		}

		#login-dialog .van-popup {
			width: 690upx;
			height: 307upx;
			border-radius: 8upx;

			.diolog {
				padding: 50upx 20upx;

				.success {
					display: flex;
					justify-content: center;
					align-items: center;

					i {
						font-size: 80upx;
						color: #ff6a44;
					}
				}

				.text {
					margin: 20upx 30upx 0;

					.p {
						line-height: 1.5;

						.span {
							color: #074690;
						}
					}
				}
			}
		}
	}
</style>
